package com.example.leetdemo.plan1;

import java.util.*;

public class Sword011 {


    public int findMaxLength(int[] nums) {
        int[][] te = new int[nums.length + 1][2];
        te[0][0] = 0; te[0][1] = 0;
        Map<Integer, List<Integer>> map = new HashMap<>();
        int m = 0;
        for(int i = 0; i < nums.length; i++) {
            te[i + 1][0] = nums[i] == 0 ? te[i][0] + 1 : te[i][0];
            te[i + 1][1] = nums[i] == 1 ? te[i][1] + 1 : te[i][1];
            int s = te[i + 1][0] - te[i + 1][1];
            if (s == 0) {
                m = i + 1;
            }
            if (map.containsKey(s)) {
                List<Integer> list = map.get(s);
                list.add(i);
                map.put(s, list);
            } else {
                List<Integer> list = new ArrayList<>();
                list.add(i);
                map.put(s, list);
            }
            //  这里直接 最新的减map里的对应第一个就好。 然后比大小
        }

        for (int i : map.keySet()) {
            int s1 = map.get(i).get(0), s2 = map.get(i).get(map.get(i).size() - 1);
//            if (map.containsKey(-i)) {
//                int b1 = map.get(-i).get(0), b2 = map.get(-i).get(map.get(-i).size() - 1);
//                m = Math.max(Math.abs(s1 - b2), m);
//                m = Math.max(Math.abs(s2 - b1), m);
//            }
            m = Math.max(s2 - s1, m);
        }
        return m;
    }

    public static void main(String[] args) {
        Sword011 sword011 = new Sword011();
        System.err.println(sword011.findMaxLength(
                new int[]{
                1,0,1,0,1,1,0,0,1,0,
                0,0,1,0,0,0,1,1,0,1,
                1,0,1,0,0,1,0,0,1,1,
                0,0,1,1,1,0,0,1,1,0,
                0,0,1,1,0,1,1,0,1,1,
                1,0,1,1,1,0,1,0,1,1,
                0,0,0,1,0,1,1,0,0,1,
                1,1,0,0,0,0,0,0,1,1,
                1,0,0,0,1,1,0,0,1,0,
                0,0,0,1,0,1,0,0,0,0}));
    }

}
